package com.guigu.dealservice.controller;

import cn.hutool.json.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.guigu.dealservice.common.AliPayConfig;
import com.guigu.dealservice.entity.EquipmentReservation;
import com.guigu.dealservice.entity.Order;
import com.guigu.dealservice.service.EquipmentReservationService;
import com.guigu.dealservice.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

//  https://natapp.cn/
// ekihat7647@sandbox.com
@RestController
@RequestMapping("/dealservice/alipay")
public class AliPayController {

    // 支付宝沙箱网关地址
    private static final String GATEWAY_URL = "https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    private static final String FORMAT = "JSON";
    private static final String CHARSET = "UTF-8";
    //签名方式
    private static final String SIGN_TYPE = "RSA2";

    @Resource
    private AliPayConfig aliPayConfig;

    @Resource
    private OrderService orderService;

    @Autowired
    private EquipmentReservationService equipmentReservationService;

    /**
     * 完成支付宝支付请求
     * @param orderNo
     * @param httpResponse
     * @throws Exception
     */
    @GetMapping("/pay/{id}/{payType}")  //  /alipay/pay?orderNo=xxx
    public void pay(@PathVariable("id") Integer orderNo, @PathVariable("payType") Integer payType,HttpServletResponse httpResponse) throws Exception {


        if (payType==1){

            // 查询订单信息
            Order orders = orderService.getById(orderNo);
            if (orders == null) {
                return;
            }
            //预定的支付
            // 1. 创建Client，通用SDK提供的Client，负责调用支付宝的API
            AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, aliPayConfig.getAppId(),
                    aliPayConfig.getAppPrivateKey(), FORMAT, CHARSET, aliPayConfig.getAlipayPublicKey(), SIGN_TYPE);

            // 2. 创建 Request并设置Request参数
            AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();  // 发送请求的 Request类
            request.setNotifyUrl(aliPayConfig.getNotifyUrl());

            JSONObject bizContent = new JSONObject();
            bizContent.set("out_trade_no", orders.getOrderId());  // 我们自己生成的订单编号
            bizContent.set("total_amount", orders.getDepositAmount()); // 订单的定金金额
            bizContent.set("subject","支付定金");   // 支付的名称
            bizContent.set("product_code", "FAST_INSTANT_TRADE_PAY");  // 固定配置，即时到帐
            request.setBizContent(bizContent.toString());

            request.setReturnUrl("http://localhost:5173/userorder_gerenzhongxin"); // 支付完成后自动跳转到本地页面的路径
            // 执行请求，拿到响应的结果，返回给浏览器
            String form = "";
            try {
                form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
            } catch (AlipayApiException e) {
                e.printStackTrace();
            }
            httpResponse.setContentType("text/html;charset=" + CHARSET);
            httpResponse.getWriter().write(form);// 直接将完整的表单html输出到页面
            httpResponse.getWriter().flush();
            httpResponse.getWriter().close();
        }else if(payType==2){

            // 查询订单信息
            Order orders = orderService.getById(orderNo);
            if (orders == null) {
                return;
            }
            //设备检测的支付
            // 1. 创建Client，通用SDK提供的Client，负责调用支付宝的API
            AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, aliPayConfig.getAppId(),
                    aliPayConfig.getAppPrivateKey(), FORMAT, CHARSET, aliPayConfig.getAlipayPublicKey(), SIGN_TYPE);

            // 2. 创建 Request并设置Request参数
            AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();  // 发送请求的 Request类
            request.setNotifyUrl(aliPayConfig.getNotifyUrl());

            JSONObject bizContent = new JSONObject();

            bizContent.set("out_trade_no", "INSPECTION_" + orders.getOrderId());  // 添加前缀区分
            // 检测费用 = 设备价值的 1%-3%
            BigDecimal rate = new BigDecimal("0.02"); // 2%
            BigDecimal inspectionFee =orders.getOrderAmount().multiply(rate)
                    .setScale(2, RoundingMode.HALF_UP);

            bizContent.set("total_amount",inspectionFee ); // 设备检测费用
            bizContent.set("subject","检测费用");   // 支付的名称
            bizContent.set("product_code", "FAST_INSTANT_TRADE_PAY");  // 固定配置，即时到帐
            request.setBizContent(bizContent.toString());

            request.setReturnUrl("http://localhost:5173/userorder_gerenzhongxin"); // 支付完成后自动跳转到本地页面的路径
            // 执行请求，拿到响应的结果，返回给浏览器
            String form = "";
            try {
                form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
            } catch (AlipayApiException e) {
                e.printStackTrace();
            }
            httpResponse.setContentType("text/html;charset=" + CHARSET);
            httpResponse.getWriter().write(form);// 直接将完整的表单html输出到页面
            httpResponse.getWriter().flush();
            httpResponse.getWriter().close();
        }else if (payType==3){
            // 查询订单信息
            Order orders = orderService.getById(orderNo);
            if (orders == null) {
                return;
            }
            //尾款支付
            // 1. 创建Client，通用SDK提供的Client，负责调用支付宝的API
            AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, aliPayConfig.getAppId(),
                    aliPayConfig.getAppPrivateKey(), FORMAT, CHARSET, aliPayConfig.getAlipayPublicKey(), SIGN_TYPE);

            // 2. 创建 Request并设置Request参数
            AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();  // 发送请求的 Request类
            request.setNotifyUrl(aliPayConfig.getNotifyUrl());

            JSONObject bizContent = new JSONObject();

            bizContent.set("out_trade_no", "WEIKUAN" + orders.getOrderId());  // 添加前缀区分

            bizContent.set("total_amount",orders.getBalanceAmount() ); // 设备尾款金额
            bizContent.set("subject","设备尾款金额");   // 支付的名称
            bizContent.set("product_code", "FAST_INSTANT_TRADE_PAY");  // 固定配置，即时到帐
            request.setBizContent(bizContent.toString());

            request.setReturnUrl("http://localhost:5173/userorder_gerenzhongxin"); // 支付完成后自动跳转到本地页面的路径
            // 执行请求，拿到响应的结果，返回给浏览器
            String form = "";
            try {
                form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
            } catch (AlipayApiException e) {
                e.printStackTrace();
            }
            httpResponse.setContentType("text/html;charset=" + CHARSET);
            httpResponse.getWriter().write(form);// 直接将完整的表单html输出到页面
            httpResponse.getWriter().flush();
            httpResponse.getWriter().close();
        } else if (payType==4){
            // 查询订单信息
            Order orders = orderService.getById(orderNo);
            if (orders == null) {
                return;
            }
            //小程序尾款支付
            // 1. 创建Client，通用SDK提供的Client，负责调用支付宝的API
            AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, aliPayConfig.getAppId(),
                    aliPayConfig.getAppPrivateKey(), FORMAT, CHARSET, aliPayConfig.getAlipayPublicKey(), SIGN_TYPE);

            // 2. 创建 Request并设置Request参数
            AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();  // 发送请求的 Request类
            request.setNotifyUrl(aliPayConfig.getNotifyUrl());

            JSONObject bizContent = new JSONObject();

            bizContent.set("out_trade_no", "WEIKUANAPP" + orders.getOrderId());  // 添加前缀区分

            bizContent.set("total_amount",orders.getBalanceAmount() ); // 设备尾款金额
            bizContent.set("subject","设备尾款金额");   // 支付的名称
            bizContent.set("product_code", "FAST_INSTANT_TRADE_PAY");  // 固定配置，即时到帐
            request.setBizContent(bizContent.toString());

            request.setReturnUrl("http://localhost:5173/userorder_gerenzhongxin"); // 支付完成后自动跳转到本地页面的路径
            // 执行请求，拿到响应的结果，返回给浏览器
            String form = "";
            try {
                form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
            } catch (AlipayApiException e) {
                e.printStackTrace();
            }
            httpResponse.setContentType("text/html;charset=" + CHARSET);
            httpResponse.getWriter().write(form);// 直接将完整的表单html输出到页面
            httpResponse.getWriter().flush();
            httpResponse.getWriter().close();
        }
    }

    /**
     * http://127.0.0.1:9090/alipay/notify
     * 支付宝异步回调，修改本地订单的状态以及交易单号
     * @param request
     * @throws Exception
     */
    @PostMapping("/notify")  // 注意这里必须是POST接口
    public void payNotify(HttpServletRequest request) throws Exception {
        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
            System.out.println("=========支付宝异步回调========");

            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
            }

            String sign = params.get("sign");
            String content = AlipaySignature.getSignCheckContentV1(params);
            boolean checkSignature = AlipaySignature.rsa256CheckContent(content, sign, aliPayConfig.getAlipayPublicKey(), "UTF-8"); // 验证签名
            // 支付宝验签
            if (checkSignature) {
                // 验签通过
                System.out.println("交易名称: " + params.get("subject"));
                System.out.println("交易状态: " + params.get("trade_status"));
                System.out.println("支付宝交易凭证号: " + params.get("trade_no"));
                System.out.println("商户订单号: " + params.get("out_trade_no"));
                System.out.println("交易金额: " + params.get("total_amount"));
                System.out.println("买家在支付宝唯一id: " + params.get("buyer_id"));
                System.out.println("买家付款时间: " + params.get("gmt_payment"));
                System.out.println("买家付款金额: " + params.get("buyer_pay_amount"));


                String tradeNo = params.get("out_trade_no");  // 订单编号
                String subject = params.get("subject"); // 获取交易名称
                String gmtPayment = params.get("gmt_payment");  // 支付时间
                if ("支付定金".equals(subject)) {
                // 更新订单状态为已支付，设置支付信息
                Order orders = orderService.getById(tradeNo);
                orders.setOrderStatus(1);
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                LocalDateTime paymentTime = LocalDateTime.parse(gmtPayment, formatter);
                orders.setDepositPayTime(paymentTime);
                orders.setPaymentMethod("支付宝");
                orderService.updateById(orders);

                //根据买家和设备修改预定表
                equipmentReservationService.update()
                        .eq("user_id", orders.getBuyerId())
                        .eq("equipment_id", orders.getEquipmentId())
                        .eq("reservation_status", 0)
                        .set("reservation_status", 1)
                        .set("deposit_pay_time", LocalDateTime.now())
                        .set("update_time", LocalDateTime.now())
                        .update();
            }else if(tradeNo.startsWith("INSPECTION_")){
                    // 处理检测费用支付
                    String originalOrderNo = tradeNo.replace("INSPECTION_", "");
                    //做检测操作
                    Order orders = orderService.getById(originalOrderNo);
                    orders.setInspectionStatus(1);
                    orderService.updateById(orders);
                }else if(tradeNo.startsWith("WEIKUAN")){
                    // 处理尾款
                    String originalOrderNo = tradeNo.replace("WEIKUAN", "");
                    //做检测操作
                    Order orders = orderService.getById(originalOrderNo);
                    orders.setOrderStatus(3);
                    orders.setBalancePayTime(LocalDateTime.now());
                    orderService.updateById(orders);
                }else if(tradeNo.startsWith("WEIKUANAPP")){
                    // 处理尾款
                    String originalOrderNo = tradeNo.replace("WEIKUANAPP", "");
                    //
                    Order orders = orderService.getById(originalOrderNo);
                    orders.setOrderStatus(3);
                    orders.setBalancePayTime(LocalDateTime.now());
                    orderService.updateById(orders);
                }
            }
        }
    }

}
